package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.application.MyApplication;
import com.sendpo.zjx.sendpo.domain.AppDomain;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.GlideCatchUtil;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zjx on 2018
 */

public class UserSetActivity extends AppCompatActivity {
    private Dialog dialog;
    public static final int MODIFY_PASS = 10101;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.acnumber_iv)
    ImageView acnumberIv;
    @BindView(R.id.ac_level)
    TextView acLevel;
    @BindView(R.id.acsecuity_bt)
    RelativeLayout acsecuityBt;
    @BindView(R.id.shiping_level)
    TextView shipingLevel;
    @BindView(R.id.shiping_level_iv)
    ImageView shipingLevelIv;
    @BindView(R.id.shiping_level_type)
    TextView shipingLevelType;
    @BindView(R.id.shiming_bt)
    RelativeLayout shimingBt;
    @BindView(R.id.clear_tv)
    TextView clearTv;
    @BindView(R.id.clearbt)
    RelativeLayout clearbt;
    @BindView(R.id.update_tv)
    TextView updateTv;
    @BindView(R.id.update_bt)
    RelativeLayout updateBt;
    @BindView(R.id.about_tv)
    TextView aboutTv;
    @BindView(R.id.about_bt)
    RelativeLayout aboutBt;
    @BindView(R.id.nologinbt)
    Button nologinbt;
    private Dialog clear_dialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_set);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
        MyApplication.addActivity(this);
    }

    private void initComponent() {
        this.clear_dialog = new Dialog(this);
        this.clear_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        this.clear_dialog.setContentView(R.layout.dialog_clearmemory);
        clear_dialog.findViewById(R.id.exit_bt)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        clear_dialog.dismiss();
                    }
                });
        clear_dialog.findViewById(R.id.ok_bt)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        clear_dialog.dismiss();
                        x.image().clearMemCache();
                        x.image().clearCacheFiles();
                        GlideCatchUtil.getInstance().clearCacheMemory();
                        GlideCatchUtil.getInstance().clearCacheDiskSelf();
                        GlideCatchUtil.getInstance().cleanCatchDisk();
                        Toast.makeText(UserSetActivity.this.getApplicationContext(), "清除完成", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    @Override
    protected void onStart() {
        super.onStart();
        webUserServer();

    }

    @OnClick(value = {R.id.backbt,R.id.nologinbt,R.id.clearbt,R.id.update_bt,R.id.acsecuity_bt,R.id.about_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case  R.id.nologinbt:
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.clearbt:
                clear_dialog.show();
                break;
            case R.id.update_bt:
                initVersion();
                break;
            case R.id.acsecuity_bt:
            startActivityForResult(new Intent(this, UserSecuityActivity.class), MODIFY_PASS);
                return;
            case R.id.about_bt:
           Tools.redirectActivity(this, AboutMyselfActiviy.class);
                return;
        }
    }

    public void webUserServer() {
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", userList.get(0).getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                switch (userDomain.getState()) {
                    case HttpCode.SUCCESS:
                        User user = userDomain.getData();
                        user.setId(userList.get(0).getId());
                        Xutils.update(getApplication(), user);
                        locationUserServer();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void locationUserServer()
    {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if(userList==null||userList.size()==0){
            return;
        }
       User user=userList.get(0);
        if(TextUtils.isEmpty(user.getUserIphone())){
          acLevel.setText("小");
        }else{
            acLevel.setText("中");
        }
         switch (user.getUserRealnamestate()){
             case 0:
                 shipingLevelType.setText("未实名认证");
                 shimingBt.setOnClickListener(new View.OnClickListener()
                 {
                     public void onClick(View paramAnonymousView)
                     {
                         Tools.redirectActivity(UserSetActivity.this, UserShimingActivity.class);
                     }
                 });
                 break;
             case 1:
                 this.shipingLevelType.setText("实名审核中");
                 shimingBt.setOnClickListener(new View.OnClickListener()
                 {
                     public void onClick(View paramAnonymousView)
                     {

                     }
                 });
                 break;
             case 2:
                 this.shipingLevelType.setText("已实名认证");
                 shimingBt.setOnClickListener(new View.OnClickListener()
                 {
                     public void onClick(View paramAnonymousView)
                     {

                     }
                 });
                 break;
             case 3:
                 this.shipingLevelType.setText("未通过审核");
                 this.shimingBt.setOnClickListener(new View.OnClickListener()
                 {
                     public void onClick(View paramAnonymousView)
                     {
                         Tools.redirectActivity(UserSetActivity.this, UserShimingActivity.class);
                     }
                 });
                 break;
         }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
           if(RESULT_OK!=resultCode){
               return;
           }
         switch (requestCode){
             case MODIFY_PASS:
                 setResult(RESULT_OK);
                 finish();
                 break;
         }
    }

   public void initVersion(){
         Map<String,String> map=new HashMap<>();
        Xutils.GET(HttpUrl.appquery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                 Gson gson=new Gson();
              final   AppDomain domain=gson.fromJson(result, AppDomain.class);
                 switch (domain.getState()){
                     case HttpCode.SUCCESS:
                       if(Tools.getVersionCode(UserSetActivity.this)>=domain.getData().getAppCode()){
                           Toast.makeText(getApplicationContext(),"已经是最新版本",Toast.LENGTH_SHORT).show();
                       }else{
                           dialog = new Dialog(UserSetActivity.this);
                           dialog.setCanceledOnTouchOutside(false);
                           dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                           dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                           dialog.setContentView(R.layout.layout_alert_updateversion);
                           ((TextView)dialog.findViewById(R.id.updateversion_versionname))
                                   .setText(domain.getData().getAppVersion());
                           ((Button)dialog.findViewById(R.id.updateversion_exit))
                                   .setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View view) {
                                           dialog.dismiss();
                                       }
                                   });
                           ((Button)dialog.findViewById(R.id.updateversion_start))
                                   .setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View view) {
                                           dialog.dismiss();

                                           Xutils.DownloadLoadFile(domain.getData().getAppUrl(), getExternalCacheDir().getAbsolutePath() + "/songbao.apk", new ProgressCallback<File>() {
                                               @Override
                                               public void onWaiting() {

                                               }

                                               @Override
                                               public void onStarted() {
                             Toast.makeText(getApplicationContext(),"下载开始",Toast.LENGTH_SHORT).show();
                                               }

                                               @Override
                                               public void onLoading(long total, long current, boolean isDownloading) {

                                               }

                                               @Override
                                               public void onSuccess(File result) {
                                                   Intent intent = new Intent("android.intent.action.VIEW");
                                                   if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                                                       intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                                       intent.setDataAndType(FileProvider.getUriForFile(UserSetActivity.this, "com.sendpo.zjx.sendpo.fileProvider", result), "application/vnd.android.package-archive");
                                                   }else{
                                                       intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
                                                   }
                                                   UserSetActivity.this.startActivity(intent);
                                                   System.out.println("************************result:"+result);
                                               }
                                               @Override
                                               public void onError(Throwable ex, boolean isOnCallback) {
                                                       Toast.makeText(getApplicationContext(),"下载失败",Toast.LENGTH_SHORT).show();
                                               }

                                               @Override
                                               public void onCancelled(CancelledException cex) {

                                               }

                                               @Override
                                               public void onFinished() {

                                               }
                                           });
                                       }
                                   });
                           dialog.show();
                       }
                         break;
                 }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"无法得到最新版本",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
   }


}
